/*
 * 文章详情页面组件 - Article Detail Page Component
 * 展示文章内容、评论、点赞、收藏等功能
 */

import React, { useState, useEffect, useRef } from 'react';
import { useParams } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  message,
  Spin,
  Card,
  Space,
  Divider,
  Typography,
  Row,
  Col
} from 'antd';
import {
  StarOutlined,
  StarFilled,
  CommentOutlined,
  EyeOutlined,
  CalendarOutlined,
  UserOutlined,
  UnorderedListOutlined,
  LikeOutlined,
  HeartOutlined,
  HeartFilled
} from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import { getPostDetailWithStats, toggleLike, toggleFavourite } from '../../services/Post/api';
import CommentSection from './components/CommentSection';
import { useUserId } from '../../hooks/useUserId';
import styles from './details.less';
import 'highlight.js/styles/github-dark.css';

const { Title, Text } = Typography;

interface PostDetailData {
  post: {
    id: number;
    title: string;
    content: string;
    htmlContent?: string;
    contentType?: string;
    createBy: number;
    createTime: string;
    updateTime: string;
    coverImage?: string;
  };
  likeCount: number;
  favouriteCount: number;
  commentCount: number;
  isLiked: boolean;
  isFavourited: boolean;
}

interface TocItem {
  key: string;
  href: string;
  title: string;
  level: number;
  children?: TocItem[];
  expanded?: boolean;
}

const ArticleDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(true);
  const [postData, setPostData] = useState<PostDetailData | null>(null);
  const [actionLoading, setActionLoading] = useState(false);
  const [tocItems, setTocItems] = useState<TocItem[]>([]);
  const [flatTocItems, setFlatTocItems] = useState<TocItem[]>([]);
  const [activeHeading, setActiveHeading] = useState<string>('');
  const contentRef = useRef<HTMLDivElement>(null);
  const tocContainerRef = useRef<HTMLDivElement>(null);
  const commentSectionRef = useRef<HTMLDivElement>(null);

  // 随机目录颜色
  const tocColors = ['#5B9BD5', '#E6B800', '#D97373', '#6FB583']; // 柔和的蓝、黄、红、绿
  const [tocColor] = useState(() => tocColors[Math.floor(Math.random() * tocColors.length)]);


  const userIdString = useUserId();
  const currentUserId = userIdString ? Number(userIdString) : undefined;

  // 扁平化目录树
  const flattenTocItems = (items: TocItem[]): TocItem[] => {
    const result: TocItem[] = [];
    items.forEach(item => {
      result.push(item);
      if (item.children && item.children.length > 0) {
        result.push(...flattenTocItems(item.children));
      }
    });
    return result;
  };

  // 提取文章目录并构建树形结构
  const extractToc = (content: string): TocItem[] => {
    const lines = content.split('\n');
    const flatToc: TocItem[] = [];
    let inCodeBlock = false;
    let inYamlBlock = false;

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const trimmedLine = line.trim();

      // 检查代码块开始/结束
      if (trimmedLine.startsWith('```')) {
        inCodeBlock = !inCodeBlock;
        continue;
      }

      // 检查YAML前置元数据块
      if (trimmedLine === '---') {
        // 如果是第一行的---，或者已经在YAML块中遇到结束的---，则切换状态
        if (i === 0 || inYamlBlock) {
          inYamlBlock = !inYamlBlock;
        }
        // 如果不在YAML块中，且当前行是---，检查是否应该开始YAML块
        // 允许在文档开头有标题后再有YAML块
        else if (!inYamlBlock) {
          // 检查前面是否只有空行、注释或标题
          const precedingLines = lines.slice(0, i);
          const hasOnlyValidPrecedingContent = precedingLines.every(l => {
            const trimmed = l.trim();
            return trimmed === '' || trimmed.startsWith('#') || trimmed.startsWith('//');
          });
          if (hasOnlyValidPrecedingContent) {
            inYamlBlock = true;
          }
        }
        continue;
      }

      // 跳过代码块和YAML块中的内容
      if (inCodeBlock || inYamlBlock) {
        continue;
      }

      // 匹配标题
      const headingMatch = trimmedLine.match(/^(#{1,6})\s+(.+)$/);
      if (headingMatch) {
        const title = headingMatch[2].trim();

        // 过滤掉可能的YAML属性、链接、代码等
        if (title.length > 0 &&
          !title.includes(':') &&
          !title.startsWith('http') &&
          !title.startsWith('`') &&
          !title.match(/^\[.*\]\(.*\)$/)) {

          const level = headingMatch[1].length;
          const key = `heading-${flatToc.length}`;
          const href = `#${key}`;

          flatToc.push({
            key,
            href,
            title,
            level,
            children: [],
            expanded: level <= 2 // 默认展开一二级标题
          });
        }
      }
    }

    // 构建树形结构
    const buildTree = (items: TocItem[]): TocItem[] => {
      const result: TocItem[] = [];
      const stack: TocItem[] = [];

      for (const item of items) {
        // 找到合适的父级
        while (stack.length > 0 && stack[stack.length - 1].level >= item.level) {
          stack.pop();
        }

        if (stack.length === 0) {
          // 顶级项目
          result.push(item);
        } else {
          // 添加到父级的children中
          const parent = stack[stack.length - 1];
          if (!parent.children) parent.children = [];
          parent.children.push(item);
        }

        stack.push(item);
      }

      return result;
    };

    return buildTree(flatToc);
  };

  const fetchPostDetail = async () => {
    try {
      // setLoading(true);
      console.log('fetchPostDetail', Number(id), currentUserId);
      const response = await getPostDetailWithStats(Number(id), currentUserId);
      if (response.success) {
        let postData = response.data;
        
        // 如果是匿名用户，从localStorage读取点赞状态
        if (!currentUserId) {
          const likedPostsKey = 'anonymous_liked_posts';
          const likedPosts = JSON.parse(localStorage.getItem(likedPostsKey) || '[]');
          const postIdStr = postData.post.id.toString();
          postData.isLiked = likedPosts.includes(postIdStr);
        }
        
        setPostData(postData);
        // 提取目录
        if (response.data.post.content) {
          const toc = extractToc(response.data.post.content);
          setTocItems(toc);
          setFlatTocItems(flattenTocItems(toc));
        }
      } else {
        message.error('获取文章详情失败11');
      }
    } catch (error) {
      message.error('获取文章详情失败222');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      fetchPostDetail();
    }
  }, [id, currentUserId]);

  // 切换展开状态
  const toggleExpanded = (targetKey: string) => {
    const updateExpanded = (items: TocItem[]): TocItem[] => {
      return items.map(item => {
        if (item.key === targetKey) {
          return { ...item, expanded: !item.expanded };
        }
        if (item.children) {
          return { ...item, children: updateExpanded(item.children) };
        }
        return item;
      });
    };

    const updatedTocItems = updateExpanded(tocItems);
    setTocItems(updatedTocItems);
    setFlatTocItems(flattenTocItems(updatedTocItems));
  };

  // 检查当前激活的标题是否在某个父级的子项中（且未展开）
  const isActiveInCollapsedChildren = (item: TocItem): boolean => {
    if (!item.children || item.children.length === 0) return false;
    
    // 递归检查子项
    for (const child of item.children) {
      if (child.key === activeHeading) return true;
      if (isActiveInCollapsedChildren(child)) return true;
    }
    return false;
  };

  // 渲染树形目录
  const renderTocTree = (items: TocItem[]): React.ReactNode => {
    return items.map(item => {
      const isDirectActive = item.key === activeHeading;
      // 如果子项未展开但包含当前激活的标题，则高亮父级
      const isParentActive = !item.expanded && isActiveInCollapsedChildren(item);
      const isActive = isDirectActive || isParentActive;
      
      return (
        <div key={item.key} className={`${styles.tocItem} ${styles[`tocLevel${item.level}`]}`}>
          <div className={`${styles.tocItemContent} ${isActive ? styles.active : ''}`}>
            {item.children && item.children.length > 0 && (
              <span
                className={`${styles.tocToggle} ${item.expanded ? styles.expanded : ''}`}
                onClick={() => toggleExpanded(item.key)}
              >
                ▶
              </span>
            )}
            <span
              className={styles.tocLink}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                const element = document.getElementById(item.key);
                if (element) {
                  const offsetTop = element.offsetTop - 100; // 调整偏移量，避免被固定头部遮挡
                  window.scrollTo({ top: offsetTop, behavior: 'smooth' });
                }
              }}
            >
              {item.title}
            </span>
          </div>
          {item.children && item.children.length > 0 && item.expanded && (
            <div className={styles.tocChildren}>
              {renderTocTree(item.children)}
            </div>
          )}
        </div>
      );
    });
  };

  // 在内容渲染后添加锚点（用于 htmlContent 模式）
  useEffect(() => {
    if (postData && contentRef.current && flatTocItems.length > 0 && postData.post.htmlContent) {
      const headings = contentRef.current.querySelectorAll('h1, h2, h3, h4, h5, h6');
      let tocIndex = 0;
      
      headings.forEach((heading) => {
        const headingText = heading.textContent?.trim() || '';
        
        // 在 toc 中查找匹配的标题
        if (tocIndex < flatTocItems.length) {
          const tocItem = flatTocItems[tocIndex];
          // 检查标题文本是否匹配
          const cleanHeadingText = headingText.replace(/^#+\s*/, '').trim();
          if (cleanHeadingText === tocItem.title || headingText === tocItem.title) {
            heading.id = tocItem.key;
            tocIndex++;
          }
        }
      });
    }
  }, [postData, flatTocItems]);

  // 滚动监听，高亮当前可见的标题
  useEffect(() => {
    const handleScroll = () => {
      if (!contentRef.current) return;

      const headings = contentRef.current.querySelectorAll('h1, h2, h3, h4, h5, h6');
      const scrollPosition = window.scrollY + 150; // 偏移量，提前高亮

      // 找到当前滚动位置对应的标题
      let currentHeading = '';
      headings.forEach((heading) => {
        const headingTop = (heading as HTMLElement).offsetTop;
        if (scrollPosition >= headingTop) {
          currentHeading = heading.id;
        }
      });

      setActiveHeading(currentHeading);
    };

    // 初始执行一次
    handleScroll();

    // 添加滚动监听
    window.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [postData]);

  // 自动滚动目录到激活项
  useEffect(() => {
    if (!activeHeading || !tocContainerRef.current) return;

    // 查找激活的目录项元素
    const activeElement = tocContainerRef.current.querySelector(`.${styles.active}`);
    if (activeElement) {
      // 滚动到可视区域
      activeElement.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'nearest'
      });
    }
  }, [activeHeading]);

  // 监听页面滚动，显示滚动条
  useEffect(() => {
    let scrollTimer: NodeJS.Timeout;
    
    const handlePageScroll = () => {
      // 添加滚动类
      document.body.classList.add('scrolling');
      
      // 清除之前的定时器
      clearTimeout(scrollTimer);
      
      // 滚动停止1.5秒后开始淡出滚动条（给0.8秒时间淡出）
      scrollTimer = setTimeout(() => {
        document.body.classList.remove('scrolling');
      }, 1500);
    };
    
    window.addEventListener('scroll', handlePageScroll, { passive: true });
    
    return () => {
      window.removeEventListener('scroll', handlePageScroll);
      clearTimeout(scrollTimer);
    };
  }, []);

  // 监听目录滚动，显示滚动条
  useEffect(() => {
    if (!tocContainerRef.current) return;
    
    let scrollTimer: NodeJS.Timeout;
    const tocElement = tocContainerRef.current;
    
    const handleTocScroll = () => {
      // 添加滚动类
      tocElement.classList.add('scrolling');
      
      // 清除之前的定时器
      clearTimeout(scrollTimer);
      
      // 滚动停止1.5秒后开始淡出滚动条（给0.8秒时间淡出）
      scrollTimer = setTimeout(() => {
        tocElement.classList.remove('scrolling');
      }, 1500);
    };
    
    tocElement.addEventListener('scroll', handleTocScroll, { passive: true });
    
    return () => {
      tocElement.removeEventListener('scroll', handleTocScroll);
      clearTimeout(scrollTimer);
    };
  }, [tocContainerRef.current]);

  const handleLike = async () => {
    if (!postData) return;

    try {
      setActionLoading(true);
      
      // 匿名用户点赞逻辑
      if (!currentUserId) {
        const likedPostsKey = 'anonymous_liked_posts';
        const likedPosts = JSON.parse(localStorage.getItem(likedPostsKey) || '[]');
        const postIdStr = postData.post.id.toString();
        const isCurrentlyLiked = likedPosts.includes(postIdStr);
        
        // 调用后端接口（匿名用户）
        const response = await toggleLike(postData.post.id);
        
        if (response.success) {
          // 更新本地存储
          if (isCurrentlyLiked) {
            // 取消点赞
            const updatedLikes = likedPosts.filter((id: string) => id !== postIdStr);
            localStorage.setItem(likedPostsKey, JSON.stringify(updatedLikes));
            setPostData(prev => prev ? {
              ...prev,
              isLiked: false,
              likeCount: response.data.likeCount
            } : null);
            message.success('取消点赞成功');
          } else {
            // 点赞
            likedPosts.push(postIdStr);
            localStorage.setItem(likedPostsKey, JSON.stringify(likedPosts));
            setPostData(prev => prev ? {
              ...prev,
              isLiked: true,
              likeCount: response.data.likeCount
            } : null);
            message.success('点赞成功');
          }
        }
        return;
      }

      // 登录用户点赞逻辑
      const response = await toggleLike(postData.post.id, currentUserId);
      if (response.success) {
        setPostData(prev => prev ? {
          ...prev,
          isLiked: response.data.isLiked,
          likeCount: response.data.likeCount
        } : null);
        message.success(response.data.isLiked ? '点赞成功' : '取消点赞成功');
      } else {
        message.error('操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    } finally {
      setActionLoading(false);
    }
  };

  const handleFavourite = async () => {
    if (!postData) return;
    
    // 检查是否为匿名用户（15位ID）或未登录
    if (!currentUserId || currentUserId.toString().length === 15) {
      message.warning('收藏功能需要登录哦');
      return;
    }

    try {
      setActionLoading(true);
      const response = await toggleFavourite(postData.post.id, currentUserId);
      if (response.success) {
        setPostData(prev => prev ? {
          ...prev,
          isFavourited: response.data.isFavourited,
          favouriteCount: response.data.favouriteCount
        } : null);
        message.success(response.data.isFavourited ? '收藏成功' : '取消收藏成功');
      } else {
        message.error('操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    } finally {
      setActionLoading(false);
    }
  };

  // 跳转到评论区
  const scrollToComments = () => {
    if (commentSectionRef.current) {
      const offsetTop = commentSectionRef.current.offsetTop - 100;
      window.scrollTo({ top: offsetTop, behavior: 'smooth' });
    }
  };

  if (loading) {
    return (
      <PageContainer ghost>
        <div className={styles.loadingContainer}>
          <Spin size="large" />
        </div>
      </PageContainer>
    );
  }

  if (!postData) {
    return (
      <PageContainer ghost>
        <div className={styles.errorContainer}>
          <Text type="secondary">文章不存在或已被删除</Text>
        </div>
      </PageContainer>
    );
  }

  const { post, likeCount, favouriteCount, commentCount, isLiked, isFavourited } = postData;

  return (
    <PageContainer ghost>
      <div className={styles.container}>
        <Row gutter={24}>
          <Col xs={24} lg={17}>
            {/* 文章主体内容 */}
            <Card className={styles.articleCard}>
              {/* 文章头部信息 */}
              <div className={styles.articleHeader}>
                <Title level={1} className={styles.articleTitle}>
                  {post.title}
                </Title>

                <div className={styles.articleMeta}>
                  <Space size="middle" style={{ 
                    width: '100%', 
                    display: 'flex', 
                    justifyContent: 'center' 
                  }}>
                    <Space style={{ 
                      padding: '8px 14px', 
                      borderRadius: '10px', 
                      background: 'linear-gradient(135deg, rgba(240, 242, 245, 0.6), rgba(230, 235, 245, 0.8))',
                      border: '1px solid rgba(24, 144, 255, 0.1)',
                      boxShadow: '0 2px 4px rgba(0, 0, 0, 0.03)',
                      transition: 'all 0.3s ease',
                      cursor: 'default'
                    }}>




                      {/* 作者图标 */}
                      <UserOutlined style={{ 
                        color: '#1890ff', 
                        fontSize: '18px',
                        filter: 'drop-shadow(0 2px 8px rgba(24, 144, 255, 0.4))'
                      }} />


                      
                      <Text type="secondary" style={{ fontWeight: 500 }}>作者 {post.createBy}</Text>
                    </Space>
                    <Space style={{ 
                      flex: 1,
                      padding: '8px 14px', 
                      borderRadius: '10px', 
                      background: 'linear-gradient(135deg, rgba(240, 242, 245, 0.6), rgba(230, 235, 245, 0.8))',
                      border: '1px solid rgba(82, 196, 26, 0.1)',
                      boxShadow: '0 2px 4px rgba(0, 0, 0, 0.03)',
                      transition: 'all 0.3s ease',
                      cursor: 'default',
                      justifyContent: 'center'
                    }}>

                       {/* 日期图标 */}
                      <CalendarOutlined style={{ 
                        color: '#52c41a', 
                        fontSize: '18px',
                        filter: 'drop-shadow(0 2px 8px rgba(82, 196, 26, 0.4))'
                      }} />



                      <Text type="secondary" style={{ fontWeight: 500 }}>{new Date(post.createTime).toLocaleDateString()}</Text>
                    </Space>
                    <Space style={{ 
                      flex: 1,
                      padding: '8px 14px', 
                      borderRadius: '10px', 
                      background: 'linear-gradient(135deg, rgba(240, 242, 245, 0.6), rgba(230, 235, 245, 0.8))',
                      border: '1px solid rgba(250, 173, 20, 0.1)',
                      boxShadow: '0 2px 4px rgba(0, 0, 0, 0.03)',
                      transition: 'all 0.3s ease',
                      cursor: 'default',
                      justifyContent: 'center'
                    }}>


                      {/* 阅读量图标 */}
                      <EyeOutlined style={{ 
                        color: '#faad14', 
                        fontSize: '18px',
                        filter: 'drop-shadow(0 2px 8px rgba(250, 173, 20, 0.4))'
                      }} />


                      <Text type="secondary" style={{ fontWeight: 500 }}>阅读量 0</Text>
                    </Space>
                    <Space style={{ 
                      flex: 1,
                      padding: '8px 14px', 
                      borderRadius: '10px', 
                      background: 'linear-gradient(135deg, rgba(240, 242, 245, 0.6), rgba(230, 235, 245, 0.8))',
                      border: '1px solid rgba(235, 47, 150, 0.1)',
                      boxShadow: '0 2px 4px rgba(0, 0, 0, 0.03)',
                      transition: 'all 0.3s ease',
                      cursor: 'default',
                      justifyContent: 'center'
                    }}>


                      {/* 评论图标 */}
                      <CommentOutlined style={{ 
                        color: '#eb2f96', 
                        fontSize: '18px',
                        filter: 'drop-shadow(0 2px 8px rgba(235, 47, 150, 0.4))'
                      }} />


                      <Text type="secondary" style={{ fontWeight: 500 }}>{commentCount} 评论</Text>
                    </Space>
                  </Space>
                </div>
              </div>

              {/* 保持间距但不显示横线 */}
              <div style={{ height: '24px' }}></div>

              {/* 文章上部目录 - 只显示一级标题 */}
              {tocItems.filter(item => item.level === 1).length > 0 && (
                <Card size="small" className={styles.topTocCard}>
                  <div className={styles.topTocContent}>
                    <Title level={5} style={{ color: tocColor, fontSize: '18px' }}>
                      <UnorderedListOutlined style={{ marginRight: 8 }} />
                      文章目录
                    </Title>
                    <div className={styles.topTocList}>
                      {tocItems.filter(item => item.level === 1).map(item => (
                        <span
                          key={item.key}
                          className={styles.topTocItem}
                          onClick={(e) => {
                            e.preventDefault();
                            const element = document.getElementById(item.key);
                            if (element) {
                              const offsetTop = element.offsetTop - 100;
                              window.scrollTo({ top: offsetTop, behavior: 'smooth' });
                            }
                          }}
                        >
                          {item.title}
                        </span>
                      ))}
                    </div>
                  </div>
                </Card>
              )}

              {/* 文章内容 */}
              <div className={styles.articleContent} ref={contentRef}>
                {post.htmlContent ? (
                  // 如果后端已经渲染了HTML，直接显示
                  <div dangerouslySetInnerHTML={{ __html: post.htmlContent }} />
                ) : (
                  // 否则使用ReactMarkdown渲染原始Markdown
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    rehypePlugins={[rehypeHighlight]}
                    components={{
                      // 自定义标题样式，添加锚点ID
                      h1: ({ children, ...props }) => {
                        const title = children?.toString() || '';
                        const tocItem = flatTocItems.find(item => item.title === title);
                        const id = tocItem?.key || '';
                        return <h1 id={id} {...props}>{children}</h1>;
                      },
                      h2: ({ children, ...props }) => {
                        const title = children?.toString() || '';
                        const tocItem = flatTocItems.find(item => item.title === title);
                        const id = tocItem?.key || '';
                        return <h2 id={id} {...props}>{children}</h2>;
                      },
                      h3: ({ children, ...props }) => {
                        const title = children?.toString() || '';
                        const tocItem = flatTocItems.find(item => item.title === title);
                        const id = tocItem?.key || '';
                        return <h3 id={id} {...props}>{children}</h3>;
                      },
                      h4: ({ children, ...props }) => {
                        const title = children?.toString() || '';
                        const tocItem = flatTocItems.find(item => item.title === title);
                        const id = tocItem?.key || '';
                        return <h4 id={id} {...props}>{children}</h4>;
                      },
                      h5: ({ children, ...props }) => {
                        const title = children?.toString() || '';
                        const tocItem = flatTocItems.find(item => item.title === title);
                        const id = tocItem?.key || '';
                        return <h5 id={id} {...props}>{children}</h5>;
                      },
                      h6: ({ children, ...props }) => {
                        const title = children?.toString() || '';
                        const tocItem = flatTocItems.find(item => item.title === title);
                        const id = tocItem?.key || '';
                        return <h6 id={id} {...props}>{children}</h6>;
                      },
                      // 自定义代码块样式
                      code: ({ inline, className, children, ...props }: any) => {
                        const match = /language-(\w+)/.exec(className || '');
                        const language = match ? match[1] : '';

                        return !inline ? (
                          <div className={styles.codeBlockWrapper}>
                            {language && (
                              <div className={styles.codeBlockHeader}>
                                <span className={styles.codeLanguage}>{language}</span>
                              </div>
                            )}
                            <pre className={`${className} ${styles.codeBlock}`}>
                              <code {...props}>
                                {children}
                              </code>
                            </pre>
                          </div>
                        ) : (
                          <code className={`${className} ${styles.inlineCode}`} {...props}>
                            {children}
                          </code>
                        );
                      },
                      // 自定义表格样式
                      table: ({ children }) => (
                        <div className={styles.tableWrapper}>
                          <table className={styles.markdownTable}>{children}</table>
                        </div>
                      ),
                      // 自定义图片样式
                      img: ({ src, alt, ...props }) => (
                        <span className={styles.imageWrapper} style={{ display: 'block' }}>
                          <img
                            src={src}
                            alt={alt}
                            className={styles.markdownImage}
                            {...props}
                          />
                          {alt && <span className={styles.imageCaption} style={{ display: 'block' }}>{alt}</span>}
                        </span>
                      ),
                      // 自定义链接样式
                      a: ({ href, children, ...props }) => (
                        <a
                          href={href}
                          target="_blank"
                          rel="noopener noreferrer"
                          className={styles.markdownLink}
                          {...props}
                        >
                          {children}
                        </a>
                      ),
                      // 自定义引用块样式
                      blockquote: ({ children }) => (
                        <blockquote className={styles.markdownBlockquote}>
                          {children}
                        </blockquote>
                      ),
                      // 自定义列表样式
                      ul: ({ children, ...props }) => (
                        <ul className={styles.markdownList} {...props}>{children}</ul>
                      ),
                      ol: ({ children, ...props }) => (
                        <ol className={styles.markdownList} {...props}>{children}</ol>
                      ),
                      // 自定义段落样式
                      p: ({ children, ...props }) => (
                        <p className={styles.markdownParagraph} {...props}>{children}</p>
                      )
                    }}
                  >
                    {post.content}
                  </ReactMarkdown>
                )}
              </div>

              <Divider />

              {/* 文章操作按钮 */}
              <div className={styles.articleActions}>
                <Space size="large">
                  <Button
                    type={isLiked ? 'primary' : 'default'}
                    icon={isLiked ? <HeartFilled /> : <HeartOutlined />}
                    loading={actionLoading}
                    onClick={handleLike}
                    className={styles.actionButton}
                  >
                    {isLiked ? '已点赞' : '点赞'} ({likeCount})
                  </Button>

                  <Button
                    type={isFavourited ? 'primary' : 'default'}
                    icon={isFavourited ? <StarFilled /> : <StarOutlined />}
                    loading={actionLoading}
                    onClick={handleFavourite}
                    className={styles.actionButton}
                  >
                    {isFavourited ? '已收藏' : '收藏'} ({favouriteCount})
                  </Button>
                </Space>
              </div>
            </Card>

            {/* 评论区 */}
            <div ref={commentSectionRef}>
              <Card className={styles.commentCard} title={`评论 (${commentCount})`}>
                <CommentSection
                  postId={post.id}
                  currentUserId={currentUserId || 0}
                  onCommentCountChange={(count) => {
                    setPostData(prev => prev ? { ...prev, commentCount: count } : null);
                  }}
                />
              </Card>
            </div>
          </Col>

          <Col xs={0} lg={7}>
            {/* 侧边栏 */}
            <div className={styles.sidebarContainer}>
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                {/* 目录卡片 */}
                {tocItems.length > 0 && (
                  <Card size="small" className={styles.sideCard}>
                    <div className={styles.sideCardContent}>
                      <Title level={5} style={{ color: tocColor, fontSize: '18px' }}>
                        <UnorderedListOutlined style={{ marginRight: 8 }} />
                        文章目录
                      </Title>
                      <div className={styles.tocContainer} ref={tocContainerRef}>
                        {renderTocTree(tocItems)}
                      </div>
                    </div>
                  </Card>
                )}

                {/* 文章信息卡片 */}
                <Card size="small" className={styles.sideCard}>
                  <div className={styles.sideCardContent}>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px', marginBottom: '12px' }}>
                      <Title level={5} style={{ marginBottom: 0, fontSize: '17px' }}>文章信息</Title>
                      <Text type="secondary" style={{ fontSize: '13px', color: '#bfbfbf' }}>点击即可操作</Text>
                    </div>
                    <Space direction="vertical" size="small" style={{ width: '100%' }}>
                      <div 
                        className={styles.statItem} 
                        onClick={handleLike} 
                        style={{ cursor: 'pointer' }}
                      >
                        {isLiked ? <HeartFilled style={{ color: '#ff4d4f', fontSize: '17px' }} /> : <LikeOutlined style={{ color: '#ff4d4f', fontSize: '17px' }} />}
                        <Text style={{ fontSize: '15px' }}>{isLiked ? '已点赞' : '点赞'} {likeCount}</Text>
                      </div>
                      <div 
                        className={styles.statItem} 
                        onClick={handleFavourite} 
                        style={{ cursor: 'pointer' }}
                      >
                        {isFavourited ? <StarFilled style={{ color: '#faad14', fontSize: '17px' }} /> : <StarOutlined style={{ color: '#faad14', fontSize: '17px' }} />}
                        <Text style={{ fontSize: '15px' }}>{isFavourited ? '已收藏' : '收藏'} {favouriteCount}</Text>
                      </div>
                      <div className={styles.statItem} onClick={scrollToComments} style={{ cursor: 'pointer' }}>
                        <CommentOutlined style={{ color: '#1890ff', fontSize: '17px' }} />
                        <Text style={{ fontSize: '15px' }}>评论 {commentCount}</Text>
                      </div>
                    </Space>
                  </div>
                </Card>
              </Space>
            </div>
          </Col>
        </Row>
      </div>
    </PageContainer>
  );
};

export default ArticleDetailPage;